package priv.mill.logdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;


public class SocketDemo {
	
	private static Map<String, Servlet> maps = new HashMap<>();
	
	static{
		maps.put("/aaaa", new YueFei());
		maps.put("/bbbb", new QingHui());
	}

	private static Logger logger = Logger.getLogger(SocketDemo.class);

	public static void main(String[] args) {
		try {
			ServerSocket socket = new ServerSocket(9999);
			while(true) {
				Socket accept = socket.accept();
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						try {
							handler(accept);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void handler(Socket accept) throws IOException {
		InputStream in = accept.getInputStream();
//			int available = in.available();
//			logger.debug(available);
//			int amount = 0;
		int len;
		byte[] b = new byte[4096];
		StringBuffer stringBuffer = new StringBuffer();
		int a = 0;
		while((len=in.read(b))!=0) {
			String x = new String(b,0,len);
			stringBuffer.append(x);
			if(x.contains("\r\n\r\n")) {
				break;
			}
		}
		accept.shutdownInput();
		
		String[] split = stringBuffer.toString().split("\r\n");
		String path = split[0].split("\\s")[1];
		OutputStream out = accept.getOutputStream();
		out.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
		maps.get(path).doGet(out);
//		out.write(("<h1>this is my info"+path+"</h1>").getBytes());
//		System.out.println("over");
		accept.shutdownOutput();
		accept.close();
	}
}


